# Author ： chosen-yn
from rest_framework.exceptions import APIException
from rest_framework.views import exception_handler
from rest_framework.response import Response
from utils.common_logger import logger


def common_exception_handler(exc, context):
    # 只要出了异常，都会走到这里---》走到这里：可能是drf的错误，可能的django的错误，还可能是python错误
    # 只要出了异常，都要记录日志---》尽量详细
    request = context.get('request')
    view = context.get('view')
    # f'用户【】，访问地址【】，请求方式是【】，访问视图类【】，错误是【】'

    user = request.user.username or '匿名用户'
    path = request.get_full_path()
    method = request.method

    logger.error(f'用户【{user}】，访问地址【{path}】，请求方式是【{method}】，访问视图类【{str(view)}】，错误是【{str(exc)}】')

    response = exception_handler(exc, context)
    if response:
        if isinstance(response.data, dict):
            # drf的异常
            err = response.data.get('detail') or response.data
        elif isinstance(response.data, list):
            err = response.data[0]
        else:
            err = '服务器异常'
    else:
        # 非drf异常，又可以分很多情况，甚至是自己定义的异常
        err = str(exc)
    return Response({'code': 101, 'msg': err})
